// pages/milkyTea/milkyTea.js
// 获取应用实例
const app = getApp()
const tools = require('../../utils/util.js')

// 右侧每一类的 bar 的高度（固定）
const RIGHT_BAR_HEIGHT = 20;

// 右侧每个子类的高度（固定）
const RIGHT_ITEM_HEIGHT = 100;

// 左侧每个类的高度（固定）
const LEFT_ITEM_HEIGHT = 50

Page({

  data: {
    categoryList: [],
    user_table: 0,
    category_id: 0,
    ware_id: 0,
    // 是否显示下面的购物车
    HZL_isCat: 0,
    wareList: [],
    // 购物车的商品
    HZL_my_cat: [],
    // 购物车的数量
    HZL_num: 0,
    // HZL_price:0,
    // 左 => 右联动 右scroll-into-view 所需的id
    HZL_toView: [],
    // 右侧每类数据到顶部的距离（用来与 右 => 左 联动时监听右侧滚动到顶部的距离比较）
    HZL_eachRightItemToTop: [],
    HZL_leftToTop: 0,
    // 当前左侧选择的
    HZL_currentLeftSelect: [],
    // 数据
    constants: [

    ],
    background: [
      "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F019d4958d4e12fa801219c77f1fffc.jpg%402o.jpg&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1630628201&t=6a5d566931f246d0c1d8424ffaaeaeea",
      "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F017e8c58d87dd2a801219c77c40094.jpg&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1630628201&t=b17ade8692a1a8cb19e53e804cd55f41"
    ],
    showPop: false,
    animationData: {},
    userInfo: {
      avatar: '',
      user_name: ''
    },
    isCanShow: 0,
  },

  login: function () {
    let that = this
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log('res:', res)
        this.setData({
          userInfo: res.userInfo,
        })
        wx.login({
          success: (res) => {
            console.log('res', res)
            if (res.code) {
              wx.request({
                url: 'https://order.xiaxueruo.com/api/User/userInfo',
                data: {
                  code: res.code,
                  user_name: that.data.userInfo.nickName,
                  avatar: that.data.userInfo.avatarUrl
                },
                method: 'GET',
                success: function (res) {
                  // 接口返回openid或者一个能标识身份的标识，比如user_id
                  console.log("成功：", res.data);
                  console.log("成功：", res.data.user_id);
                  console.log("成功：", res.data.user_name);
                  console.log("成功：", res.data.avatar);

                  // 把唯一标识缓存
                  wx.setStorageSync('session3rd', res.data.session3rd)
                  wx.setStorageSync('user_id', res.data.user_id)
                  wx.setStorageSync('user_name', res.data.user_name)
                  wx.setStorageSync('avatar', res.data.avatar)

                  that.setData({
                    userInfo: {
                      avatar: res.data.avatar,
                      user_name: res.data.user_name,
                      user_id: res.data.user_id
                    },
                    isShowUserName: true
                  });
                }
              })
            }
          }
        })
      }
    })

  },

  getWareList() {
    let that = this
    console.log('------------------', that.data)
    wx.request({
      url: 'https://order.xiaxueruo.com/api/ware/index',
      method: 'GET', //get或者post
      success: function (res) {
        app.globalData.wareList = res.data.data.wareList
        console.log('---app.globalData.wareList', app.globalData.wareList) //接口返回值
        for (let item of app.globalData.wareList) {
          item.add_time = tools.formatTime(item.add_time)
        }
        console.log(res) //接口返回值
        console.log('1111111', res.data.data.wareList)
        that.setData({
          wareList: app.globalData.wareList
        })
      }
    })
  },

  getCategoryList() {
    let that = this
    console.log('------------------', that.data)
    wx.request({
      url: 'https://order.xiaxueruo.com/api/category/list',
      method: 'GET', //get或者post
      success: function (e) {
        console.log(e) //接口返回值
        console.log('1111111', e.data.data.categoryList)
        that.setData({
          categoryList: e.data.data.categoryList,
          HZL_currentLeftSelect: e.data.data.categoryList[0].category_id,
          HZL_eachRightItemToTop: that.HZL_getEachRightItemToTop(),
        })
        wx.setStorageSync('key', e.data.data.categoryList)
      }
    })
  },

  goComment: function (e) {
    console.log('---------index', e)
    console.log(e.currentTarget.dataset.id)
    let ware_id = e.currentTarget.dataset.id;

    wx.navigateTo({
      url: '../milkyTea/comment/comment?ware_id=' + ware_id,
    })
  },


  // 显示底部弹层
  showModal: function () {
    var _this = this;
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
      delay: 0
    })
    _this.animation = animation
    animation.translateY(300).step()
    _this.setData({
      animationData: animation.export(),
      showPop: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      _this.setData({
        animationData: animation.export()
      })
    }.bind(_this), 50)
  },
  // 隐藏底部弹层
  hideModal: function () {
    var _this = this;
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: "ease",
      delay: 0
    })
    _this.animation = animation
    animation.translateY(300).step()
    _this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      _this.setData({
        animationData: animation.export(),
        showPop: false
      })
    }.bind(this), 200)
  },

  /**
   * 记录swiper滚动
   */
  HZL_swiperchange: function (e) {
    var that = this;
    that.setData({
      HZL_swiper_ID: e.detail.current,
    })
  },


  /**
   * 点击分类栏
   */
  HZL_categories: function (e) {
    var that = this;
    that.setData({
      HZL_swiper_ID: e.currentTarget.dataset.index
    })
  },


  /**
   * 获取每个右侧的 bar 到顶部的距离，
   * 用来做后面的计算。
   */
  HZL_getEachRightItemToTop: function () {
    var obj = {};
    var totop = 0;
    var categoryList = wx.getStorageSync('key');
    var category_id = "goods" + categoryList[0],
      category_id;
    // 右侧第一类肯定是到顶部的距离为 0
    obj[category_id] = totop
    console.log(22222, categoryList)
    // 循环来计算每个子类到顶部的高度

    var totop = 0;
    var totop2 = 0;
    for (let i = 0; i < categoryList.length; i++) {
      // 这个的目的是 例如有两类，最后需要 0-1 1-2 2-3 的数据，所以需要一个不存在的 'last' 项，此项即为第一类加上第二类的高度。
      obj[categoryList[i] ? "goods" + categoryList[i].category_id : 'last'] = totop2;
      var temp = (RIGHT_BAR_HEIGHT + categoryList[i].wareList.length * RIGHT_ITEM_HEIGHT);
      totop += temp;
      totop2 = totop - temp / 3.5;
    }
    obj['last'] = totop2;

    console.log(obj)
    return obj
  },


  /**
   * 监听右侧的滚动事件与 HZL_eachRightItemToTop 的循环作对比
   * 从而判断当前可视区域为第几类，从而渲染左侧的对应类
   */
  right: function (e) {
    // console.log('eee',e)
    var categoryList = wx.getStorageSync('key');
    for (let i = 0; i < categoryList.length; i++) {
      let left = this.data.HZL_eachRightItemToTop["goods" + categoryList[i].category_id]
      let right = this.data.HZL_eachRightItemToTop[categoryList[i + 1] ? "goods" + categoryList[i + 1].category_id : 'last']
      // console.log(left, right);
      // console.log(e.detail);
      if (e.detail.scrollTop < right && e.detail.scrollTop >= left) {
        this.setData({
          HZL_currentLeftSelect: "goods" + categoryList[i].category_id,
          HZL_leftToTop: LEFT_ITEM_HEIGHT * i
        })
      }
    }
  },


  /**
   * 左侧类的点击事件，
   * 点击时，右侧会滚动到对应分类
   */
  left: function (e) {
    var that = this
    that.setData({
      HZL_toView: e.target.id || e.target.dataset.id,
      HZL_currentLeftSelect: e.target.id || e.target.dataset.id
    })
  },


  /**
   * 去结算按钮
   * 具体功能自己写
   */
  go: function () {
    // 用户购物车(包含选择的商品)
    console.log(this.data.HZL_my_cat)
    if (!wx.getStorageSync('user_id')) {
      this.login() //登录
    } else {
      if (this.data.HZL_my_cat == "" || this.data.HZL_my_cat == undefined) {
        wx.showToast({
          title: '请选择商品',
          icon: 'error',
          duration: 1000
        })
      } else {
        console.log("HZL_my_cat", this.data.HZL_my_cat)
        wx.setStorageSync('HZL_my_cat', this.data.HZL_my_cat)
        wx.navigateTo({
          url: '../confirm/confirm',
        })
      }
    }
  },


  /**
   * 是否显示下面的购物车
   */
  HZL_isCat: function (e) {
    var that = this;
    if (that.data.HZL_isCat == 0 && that.data.HZL_num > 0) {
      that.setData({
        HZL_isCat: 1
      })
    } else if (that.data.HZL_isCat == 1 && that.data.HZL_num > 0) {
      that.setData({
        HZL_isCat: 0
      })
    }
  },


  /**
   * 黑背景模态墙点外侧关闭
   */
  HZL_isCat_close: function (e) {
    this.setData({
      HZL_isCat: 0
    })
  },


  /**
   * 清空购物车
   */
  HZL_zero: function (e) {
    for (var i = 0; i < this.data.categoryList.length; i++) {
      for (var j = 0; j < this.data.categoryList[i].wareList.length; j++) {
        this.data.categoryList[i].wareList[j].ware_num = 0
      }
    }
    this.setData({
      HZL_isCat: 0,
      HZL_num: 0,
      HZL_my_cat: [],
      categoryList: this.data.categoryList,
    })
  },

  // ok: function (e) {
  //   var index = e.currentTarget.dataset.index;
  //   var parentIndex = e.currentTarget.dataset.parentindex;
  //   var HZL_my_cat = this.HZL_my_jia(parentIndex, index)
  //   this.setData({
  //     HZL_num: this.data.HZL_num,
  //     HZL_my_cat: HZL_my_cat,
  //     categoryList: this.data.categoryList,
  //   })
  // },

  // getGuige: function(e){
  //   this.showModal();
  //   console.log("**********",e)
  // },

  /**
   * 增加数量按钮
   */
  HZL_jia: function (e) {
    var index = e.currentTarget.dataset.index;
    var parentIndex = e.currentTarget.dataset.parentindex;
    var HZL_my_cat = this.HZL_my_jia(parentIndex, index)
    this.setData({
      HZL_num: this.data.HZL_num,
      HZL_my_cat: HZL_my_cat,
      categoryList: this.data.categoryList,
      num: this.data.num
    })
  },


  /**
   * 减少数量按钮
   */
  HZL_jian: function (e) {
    var index = e.currentTarget.dataset.index;
    var parentIndex = e.currentTarget.dataset.parentindex;
    var HZL_my_cat = this.HZL_my_jian(parentIndex, index)

    if (this.data.HZL_num == 0) {
      this.data.HZL_isCat = 0;
    } else {
      this.data.HZL_isCat = 1;
    }

    this.setData({
      HZL_num: this.data.HZL_num,
      HZL_my_cat: HZL_my_cat,
      categoryList: this.data.categoryList,
      num: this.data.num
    })
  },


  /**
   * 下面购物车增加按钮
   */
  HZL_jia1: function (e) {
    console.log(e)
    var index = e.currentTarget.dataset.index;
    var parentIndex = e.currentTarget.dataset.parentindex;
    var HZL_my_cat = this.HZL_my_jia(parentIndex, index)
    this.setData({
      HZL_num: this.data.HZL_num,
      HZL_my_cat: HZL_my_cat,
      categoryList: this.data.categoryList,
      HZL_price: this.data.HZL_price,
    })
  },


  /**
   * 下面购物车减少按钮
   */
  HZL_jian1: function (e) {
    var index = e.currentTarget.dataset.index;
    var parentIndex = e.currentTarget.dataset.parentindex;
    var HZL_my_cat = this.HZL_my_jian(parentIndex, index)

    if (this.data.HZL_num == 0) {
      this.data.HZL_isCat = 0;
    } else {
      this.data.HZL_isCat = 1;
    }

    this.setData({
      HZL_num: this.data.HZL_num,
      HZL_my_cat: HZL_my_cat,
      categoryList: this.data.categoryList,
      HZL_isCat: this.data.HZL_isCat,
      HZL_price: this.data.HZL_price,
    })
  },


  /**
   * 封装加的方法
   */
  HZL_my_jia: function (parentIndex, index) {

    // if(this.data.HZL_num > 0){
    this.data.HZL_num++;
    console.log(this.data.HZL_num)
    var index = index;
    var parentIndex = parentIndex;
    var id = this.data.categoryList[parentIndex].wareList[index].ware_id;
    var name = this.data.categoryList[parentIndex].wareList[index].ware_name;
    var num = ++this.data.categoryList[parentIndex].wareList[index].ware_num;
    var price = this.data.categoryList[parentIndex].wareList[index].ware_price;
    var type = this.data.categoryList[parentIndex].wareList[index].ware_type;
    var image = this.data.categoryList[parentIndex].wareList[index].ware_image;
    //弄一个元素判断会不会是重复的
    var mark = 'a' + index + 'b' + parentIndex + 'c' + '0' + 'd' + '0'
    var obj = {
      id: id,
      num: num,
      name: name,
      mark: mark,
      index: index,
      parentIndex: parentIndex,
      price: price,
      type: type,
      image: image
    };
    var HZL_my_cat = this.data.HZL_my_cat;
    HZL_my_cat.push(obj)

    var arr = [];
    //去掉重复的
    for (var i = 0; i < HZL_my_cat.length; i++) {
      if (obj.mark == HZL_my_cat[i].mark) {
        HZL_my_cat.splice(i, 1, obj)
      }
      if (arr.indexOf(HZL_my_cat[i]) == -1) {
        arr.push(HZL_my_cat[i]);
      }
    }

    console.log('加--', this.data.HZL_my_cat)
    return arr
    // }


  },


  /**
   * 封装减的方法
   */
  HZL_my_jian: function (parentIndex, index) {
    if (this.data.HZL_num > 0) {
      this.data.HZL_num--;
      console.log(this.data.HZL_num)
      var index = index;
      var parentIndex = parentIndex;
      var id = this.data.categoryList[parentIndex].wareList[index].ware_id;
      var name = this.data.categoryList[parentIndex].wareList[index].ware_name;
      var num = --this.data.categoryList[parentIndex].wareList[index].ware_num;
      var price = this.data.categoryList[parentIndex].wareList[index].ware_price;
      var image = this.data.categoryList[parentIndex].wareList[index].ware_image;
      var type = this.data.categoryList[parentIndex].wareList[index].ware_type;
      //弄一个元素判断会不会是重复的
      var mark = 'a' + index + 'b' + parentIndex + 'c' + '0' + 'd' + '0'
      var obj = {
        id: id,
        num: num,
        name: name,
        mark: mark,
        index: index,
        parentIndex: parentIndex,
        price: price,
        type: type,
        image: image
      };
      var HZL_my_cat = this.data.HZL_my_cat;
      HZL_my_cat.push(obj)

      var arr = [];
      //去掉重复的
      for (var i = 0; i < HZL_my_cat.length; i++) {
        if (obj.mark == HZL_my_cat[i].mark) {
          HZL_my_cat.splice(i, 1, obj)
        }
      }

      var arr1 = [];
      //当数量大于1的时候加
      for (var i = 0; i < HZL_my_cat.length; i++) {
        if (arr1.indexOf(HZL_my_cat[i]) == -1) {
          arr1.push(HZL_my_cat[i]);
          if (HZL_my_cat[i].num > 0) {
            arr.push(arr1[i])
          }
        }
      }
      console.log('减--', this.data.HZL_my_cat)
      return arr
    } else {
      return [];
    }
  },

  /**
   * 获取接口数据，控制是否显示敏感信息
   */
  checkIsCanShow() {
    wx.request({
      url: 'https://order.xiaxueruo.com/api/order/isCanShow/',
      success: res => {
        this.setData({
          isCanShow: res.data
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('options', options)
    var that = this;
    that.setData({
      user_table: options.user_table
    })
    wx.setStorageSync('user_table', options.user_table)
    this.checkIsCanShow()
    this.getCategoryList()
    this.getWareList()
    // 高度大小
    wx.getSystemInfo({
      success: function (res) {
        var HZL_height = res.windowHeight - 90
        var HZL_height1 = res.windowHeight - 110
        that.setData({
          HZL_height: HZL_height,
          HZL_height1: HZL_height1
        })
      }
    });

    // 获取服务器数据
    console.log('请求接口: 获取服务器数据')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

})